package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"vipshop/model/mysql"
	"vipshop/model/redisinit"
	"vipshop/pkg"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpLogic {
	return &UserUpLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpLogic) UserUp(in *vipshoprpc.UserUpRequest) (*vipshoprpc.UserUpResponse, error) {
	// todo: add your logic here and delete this line
	sendGet := redisinit.Rdb.Get("sendSmsUp" + in.Phone)
	if sendGet.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("id = ?", in.Id).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该账号不存在")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次密码不一致,不允许修改")
	}
	m := mysql.User{
		Model:    gorm.Model{ID: user.ID},
		Password: pkg.Md5(in.NewPassword),
	}
	mysql.DB.Debug().Updates(&m)
	redisinit.Rdb.Del("sendSmsUp" + in.Phone)
	return &vipshoprpc.UserUpResponse{
		Id: int64(m.ID),
	}, nil
}
